//    Copyright (C) 2013  <lugocreation@gmail.com>
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
package org.jpgolay.me.delivery;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyVetoException;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.*;
import org.jpgolay.gui.date.DateComboBox;
import org.jpgolay.gui.fixed.*;
import org.jpgolay.me.persistence.ObjectCRUD;
import org.jpgolay.me.sending.Sending;
import org.jpgolay.me.util.*;

// Referenced classes of package org.jpgolay.me.delivery:
//            DeliveryCRUD, DeliveryAdvanceSearchGUI
public class DeliveryController {

    public DeliveryController(SearchBox deliverySearch, TableViewer deliveryTable, Parameter param) {
        this.deliverySearch = null;
        this.deliveryTable = null;
        deliverySearchGui = null;
        calendarPeriod = null;
        dateComboBox = null;
        write = false;
        this.deliverySearch = deliverySearch;
        this.deliveryTable = deliveryTable;
        desktop = param.getDesktop();
        this.param = param;
        date = new MEDate();
        deliveryCrud = new DeliveryCRUD();
        crud = new ObjectCRUD();
        initLaw();
        initSearch();
        initTable();
    }

    private void initLaw() {
        if (param.getAccessLaw().length() >= 29 && param.getAccessLaw().charAt(29) == '1') {
            write = true;
        } else if (param.getAccessLaw().length() >= 27 && param.getAccessLaw().charAt(27) == '1') {
            write = true;
        }
    }

    private void initSearch() {
        deliverySearch.setList(new String[]{
                    "Code (client)", "Raison social (client)", "Numero de BL", "Livr\351 par"
                });
        deliverySearch.setVal("");
        deliverySearch.setAdvanceSearch(getDeliverySearchGUI());
        deliverySearch.getButtonRight().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionSearch();
            }
        });
        deliverySearch.getTextField().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionSearch();
            }
        });
    }

    private void initTable() {
        deliveryTable.setTypes(new Class[]{
                    java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
                });
        deliveryTable.setLastColumnNotEditable(1);
        deliveryTable.setCellEditable(write);
        deliveryTable.setAlternateColor(MEUtility.DELIVERY_LINE);
        deliveryTable.setColumnNames(new String[]{
                    "BL", "CLIENT", "LIVREUR", "DATE", "NOTE"
                });
        deliveryTable.setPreferredColumnSize(new int[]{
                    40, 50, 40, 50, 30
                });
        actionSearch();
    }

    private void setCalendarColumn(JTable table, TableColumn modeColumn) {
        modeColumn.setCellEditor(new DefaultCellEditor(getDateComboBox()));
        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setToolTipText("S\351l\351ctionner une date de livraison");
        modeColumn.setCellRenderer(renderer);
    }

    private DateComboBox getDateComboBox() {
        if (dateComboBox == null) {
            dateComboBox = new DateComboBox();
        }
        return dateComboBox;
    }

    private DeliveryAdvanceSearchGUI getDeliverySearchGUI() {
        if (deliverySearchGui == null) {
            deliverySearchGui = new DeliveryAdvanceSearchGUI();
            deliverySearchGui.setAgency(0);
            deliverySearchGui.getButtonRight().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionCalendarPeriod();
                }
            });
        }
        return deliverySearchGui;
    }

    private CalendarPeriod getCalendarPeriod() {
        if (calendarPeriod == null) {
            calendarPeriod = new CalendarPeriod();
            calendarPeriod.setFromDate("01/01/1991");
            calendarPeriod.setToDate("01/01/2090");
            calendarPeriod.getButtonLeft().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionCalendarPeriodOK();
                }
            });
            calendarPeriod.getButtonRight().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionCalendarPeriodCANCEL();
                }
            });
            calendarPeriod.setLocation(600, 50);
            calendarPeriod.setSize(320, 130);
        }
        return calendarPeriod;
    }

    private void actionSearch() {
        from = getCalendarPeriod().getFromDate();
        to = getCalendarPeriod().getToDate();
        agency = getDeliverySearchGUI().getAgency() + 1;
        StringBuffer sql = new StringBuffer();
        if (deliverySearch.getSelectedIndex() == 1) {
            sql.append("SELECT ventes.id, raison_sociale, livre, date_livraison, ventes.commentaire FROM ventes, clients ");
        } else {
            sql.append("SELECT id, clients_id, livre, date_livraison, commentaire FROM ventes ");
        }
        sql.append("WHERE prefixe = 'BL'");
        if (agency != 6) {
            sql.append(" AND entreprise_id=");
            sql.append(agency);
        }
        sql.append(" AND date BETWEEN '");
        sql.append(date.toMysql(from));
        sql.append("' AND '");
        sql.append(date.toMysql(to));
        switch (deliverySearch.getSelectedIndex()) {
            case 0: // '\0'
                if (deliverySearch.getVal().equals("")) {
                    sql.append("' ORDER BY clients_id");
                } else {
                    sql.append("' AND clients_id LIKE '");
                    sql.append(deliverySearch.getVal());
                    sql.append("%' ORDER BY clients_id");
                }
                break;

            case 1: // '\001'
                if (deliverySearch.getVal().equals("")) {
                    sql.append("' AND clients_id=clients.id");
                    sql.append(" ORDER BY raison_sociale");
                } else {
                    sql.append("' AND clients_id=clients.id");
                    sql.append(" AND raison_sociale LIKE '");
                    sql.append(deliverySearch.getVal());
                    sql.append("%' ORDER BY raison_sociale");
                }
                break;

            case 2: // '\002'
                if (deliverySearch.getVal().equals("")) {
                    sql.append("' ORDER BY id");
                } else {
                    sql.append("' AND id LIKE '");
                    sql.append(deliverySearch.getVal());
                    sql.append("%' ORDER BY id");
                }
                break;

            case 3: // '\003'
                if (deliverySearch.getVal().equals("")) {
                    sql.append("' ORDER BY livre");
                } else {
                    sql.append("' AND livre LIKE '");
                    sql.append(deliverySearch.getVal());
                    sql.append("%' ORDER BY livre");
                }
                break;

            default:
                if (deliverySearch.getVal().equals("")) {
                    sql.append("' ORDER BY clients_id");
                } else {
                    sql.append("' AND clients_id LIKE '");
                    sql.append(deliverySearch.getVal());
                    sql.append("%' ORDER BY clients_id");
                }
                break;
        }
        Object data[][] = deliveryCrud.getDataList(sql.toString());
        if (data != null) {
            deliveryTable.setData(data);
            setCalendarColumn(deliveryTable.getTable(), deliveryTable.getTable().getColumnModel().getColumn(3));
            deliveryTable.getTableModel().addTableModelListener(new TableModelListener() {
                public void tableChanged(TableModelEvent e) {
                    actionUpdateRow(e.getFirstRow());
                }
            });
        } else {
            deliveryTable.setData(getEmptyTable());
        }
    }

    private Object[][] getEmptyTable() {
        Object data[][] = new Object[3][5];
        for (int i = 0; i < data.length; i++) {
            data[i][0] = null;
            if (i == 1) {
                data[i][1] = "AUCUNE";
                data[i][2] = "LIVRAISON";
            } else {
                data[i][1] = null;
                data[i][2] = null;
            }
            data[i][3] = null;
            data[i][4] = null;
        }

        return data;
    }

    private void actionCalendarPeriod() {
        getCalendarPeriod().setVisible(true);
        getCalendarPeriod().toFront();
        desktop.add(getCalendarPeriod(), JLayeredPane.DEFAULT_LAYER);
        try {
            getCalendarPeriod().setSelected(true);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    }

    private void actionCalendarPeriodOK() {
        getDeliverySearchGUI().setPeriode(getCalendarPeriod().getMessage());
        actionCalendarPeriodCANCEL();
    }

    private void actionCalendarPeriodCANCEL() {
        getCalendarPeriod().setVisible(false);
        desktop.remove(getCalendarPeriod());
    }

    private void actionUpdateRow(int row) {
        if (!deliveryCrud.setUpdateRow((String) deliveryTable.getTable().getValueAt(row, 0), (String) deliveryTable.getTable().getValueAt(row, 2), (String) deliveryTable.getTable().getValueAt(row, 3), (String) deliveryTable.getTable().getValueAt(row, 4))) {
            JOptionPane.showMessageDialog(null, "Enregistrement de la livraison \340 \351chou\351 !\n(Un utilisateur a peut-\352tre modifier cette pi\350ce entre temps)");
        } else if ((String) deliveryTable.getTable().getValueAt(row, 3) != null) {
            java.util.Collection c = crud.readAll(deliveryTable.getTable().getValueAt(row, 0), 33);
            if (c != null) {
                ArrayList sendingList = new ArrayList(c);
                Iterator it = sendingList.iterator();
                it.hasNext();
                Sending sending = (Sending) it.next();
                sending.setDeliveryDate((String) deliveryTable.getTable().getValueAt(row, 3));
                crud.update(sending, 33);
            }
        }
    }
    private SearchBox deliverySearch;
    private TableViewer deliveryTable;
    private DeliveryAdvanceSearchGUI deliverySearchGui;
    private CalendarPeriod calendarPeriod;
    private DeliveryCRUD deliveryCrud;
    private ObjectCRUD crud;
    private JDesktopPane desktop;
    private String from;
    private String to;
    private int agency;
    private DateComboBox dateComboBox;
    private MEDate date;
    private boolean write;
    private Parameter param;
}
